<?php
/*
 * Other Controller that using Container
 * should extends this BaseController
 */

namespace App\Controllers;

use App\Models\User;
use Interop\Container\ContainerInterface;
use Slim\Http\Request;

class BaseController
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * 过滤字符串
     * @param $string
     * @return mixed|string
     */
    protected function clean_xss($string){
        $string = trim ( $string );
        $string = strip_tags ( $string );
        $string = htmlspecialchars ( $string );
        $string = addslashes($string);
        $no = '/%0[0-8bcef]/';
        $string = preg_replace ( $no, '', $string );
        $no = '/%1[0-9a-f]/';
        $string = preg_replace ( $no, '', $string );
        $no = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';
        $string = preg_replace ( $no, '', $string );
        return $string;
    }

    /**
     * 输出json
     * @param $err
     * @param $msg
     * @return string json字符串
     */
    protected function json($err, $msg){
        return json_encode(array("code" => $err, "msg" => $msg));
    }

    /**
     * @param $err   状态码
     * @param $msg   信息
     * @param $data  返回数据
     * @return string
     */
    protected function jsonWithData($err, $msg, $data){
        return json_encode(array("code" => $err, "msg" => $msg, "data" => $data));
    }

    /**
     * 获取用户token
     * @param Request $request
     * @return bool
     */
    protected function getToken(Request $request){
        $headers = $request->getHeader('HTTP_AUTHORIZATION');
        $regexp  = $this->container->get("settings")['jwt']['regexp'];
        if (preg_match($regexp, $headers[0], $matches)) {
            return $matches[1];
        }
        return false;
    }
}
